package dao

import (
	"errors"
	"fmt"
	"github.com/wonderivan/logger"
	"k8s-platform/db"
	"k8s-platform/model"
)

var Cicdprojects cicdprojects

type cicdprojects struct{}

func Create_apps(data model.InputData) error {
	// 创建Cicd_projects实例
	cicdProjects := model.Cicd_projects{
		Regionaname:  data.Regionaname,
		Imagesregion: data.Imagesregion,
		SelectedEnv:  data.SelectedEnv,
	}

	// 遍历AddAppList并创建AppItem实例
	for _, item := range data.AddAppList {
		appItem := model.AppItem{
			Name:            item.Name,
			SelectedVersion: item.SelectedVersion,
			CicdProjectID:   cicdProjects.ID,
		}

		// 添加到Cicd_projects的AppItems字段中
		cicdProjects.AppItems = append(cicdProjects.AppItems, appItem)
	}

	// 保存Cicd_projects到数据库
	result := db.DB.Create(&cicdProjects)
	if result.Error != nil {
		return fmt.Errorf("failed to save Cicd_projects: %w", result.Error)
	}

	return nil

}

func (*cicdprojects) List() ([]*model.Cicd_projects, error) {
	cicd_projects := []*model.Cicd_projects{}

	//tx := db.DB.Preload("Cicd_projects").Preload("AppItem").Find(&hostservers)
	tx := db.DB.Preload("AppItems").Find(&cicd_projects)
	if tx.Error != nil {
		logger.Error(fmt.Sprintf("获取hostservers列表失败，%v\n", tx.Error))
		return nil, errors.New(fmt.Sprintf("获取hostservers列表失败，%v\n", tx.Error))
	}
	return cicd_projects, nil
}
